package com.ja.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.CopyOnWriteArraySet;

import javax.servlet.http.HttpServletRequest;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import org.springframework.web.context.ContextLoader;

import com.ja.config.WebsiteStateConfig;
import com.ja.domain.Jine;
import com.ja.domain.RedPacket;
import com.ja.sevice.JineService;
import com.ja.sevice.RedPacketService;
import com.ja.util.DateUtil;

/**
 * 项目名称：cp   
 * 类名称：ChatController5.java   
 * 类描述：   聊天室群聊配置类
 * 创建人：   GL
 * 创建时间：2019年2月13日 下午12:09:39   
 * @version v1.0.0
 */
@ServerEndpoint("/all2")
public class ChatController5{
	
	private JineService jineService=(JineService)ContextLoader.getCurrentWebApplicationContext().getBean("jineService");
	
	private RedPacketService redPacketService = (RedPacketService) ContextLoader.getCurrentWebApplicationContext().getBean("redPacketService");
	
    private static CopyOnWriteArraySet<ChatController5> webSocketSet = new CopyOnWriteArraySet<ChatController5>();
    
    private static List<String> names= new ArrayList<String>();
    
    static Map<String, Session> map=new HashMap<String, Session>();//将联系人通道和联系人同时保存
    
    private static int onlineCount = 0;
    
    private Session session;
    
    private String name;
    
	@Override
	public String toString() {
		return "ChatController3 [name=" + name + "]";
	}

	/**
     * 连接建立成功调用的方法
     * @param session  可选的参数。session为与某个客户端的连接会话，需要通过它来给客户端发送数据
     */
    @OnOpen
    public void onOpen(Session session){
        this.session = session;
        webSocketSet.add(this);     //加入set中
        addOnlineCount();           //在线数加1
        this.name= session.getRequestParameterMap().get("name").get(0);//获取本次登录用户的姓名
        names.add(this.name);//将本次登录用户的姓名添加到names里面
        map.put(name, session);
    }
     
    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(){
        webSocketSet.remove(this);  //从set中删除
        subOnlineCount();           //在线数减1    
//        System.out.println("有一连接关闭！当前在线人数为" + getOnlineCount());
    }
     
    /**
     * 收到客户端消息后调用的方法
     * @param message 客户端发送过来的消息
     * @param session 可选的参数
     */
    int num = 0;
    private static boolean isFirst=true;
	@OnMessage
    public void onMessage(String message1, Session session,HttpServletRequest request) {
    	if (isFirst) {
			isFirst=false;
			while (true) {
				try {
					if(Integer.parseInt(WebsiteStateConfig.configs.get("messageFlag"))==1) {
							Jine jine = jineService.findInfoData();
							if(jine!=null){
								String n1 = jine.getName().substring(0, 2)+"**";
								String d1 = jine.getFukuanje()==0.00 ? "":jine.getFukuanje()+"";
								String d2 = jine.getTikuanje()==0.00 ? "":jine.getTikuanje()+"";
								String messages = "恭喜"+n1+jine.getState()+d1+d2+"元";
								RedPacket redPacket = new RedPacket();
								redPacket.setUserid(jine.getUserid());
								redPacket.setDesc(messages);
								redPacket.setCreattime(jine.getCltime());
								redPacketService.saveUserChatRecord(redPacket);
								this.sendMessage(messages+"k45jk459fgjdf986kjh98fgdkj3i45y89fdh4598hp90u1");
							}
							if(true){
								num = kzq(10);
								num--;
								if(num==0){
									String messages = chongzhidata();
									RedPacket redPacket = new RedPacket();
									redPacket.setUserid(0);
									redPacket.setDesc(messages);
									redPacket.setCreattime(DateUtil.getCurrTime());
									redPacketService.saveUserChatRecord(redPacket);
									for (ChatController5 item : webSocketSet) {
										item.sendMessage(messages+"k45jk459fgjdf986kjh98fgdkj3i45y89fdh4598hp90u1");
									}
								}
							}
						}
					//this.sendMessage("恭喜潘**一分时时彩201803050639期第二球1中奖168.10k45jk459fgjdf986kjh98fgdkj3i45y89fdh4598hp90u"+0);
					Thread.sleep(3000);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
    
	public String chongzhidata(){
		int num = (int) (Math.random()*100000);
		String[] str = {"充值","充值","提款"};
		return "恭喜"+getRandomString(2)+"**"+str[kzq(2)]+"成功"+num+".0元";
	}
	public  int kzq(int num) {
		while (true) {
			int ii = (int) (1 + Math.random() * (10 - 1 + 1));
			if (num >= ii) {
				return ii;
			}
		}
		
	}
	public  String getRandomString(int length){
	    //定义一个字符串（A-Z，a-z，0-9）即62位；
	    String str="zxcvbnmlkjhgfdsaqwertyuiopQWERTYUIOPASDFGHJKLZXCVBNM1234567890";
	    //由Random生成随机数
	        Random random=new Random();  
	        StringBuffer sb=new StringBuffer();
	        //长度为几就循环几次
	        for(int i=0; i<length; ++i){
	          //产生0-61的数字
	          int number=random.nextInt(62);
	          //将产生的数字通过length次承载到sb中
	          sb.append(str.charAt(number));
	        }
	        //将承载的字符转换成字符串
	        return sb.toString();
	  }
    /**
     * 发生错误时调用
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error){
        System.out.println("socket连接出现异常");
        error.printStackTrace();
    }
    /**
     * 这个方法与上面几个方法不一样。没有用注解，是根据自己需要添加的方法。
     * @param message
     * @throws IOException
     */
    public void sendMessage(String message){
    	try {
			this.session.getBasicRemote().sendText(message);
		} catch (Exception e) {
		}
    }
    
    public void sendMessageToPeople(String toName,String fromName,String message) throws IOException {
    	this.session.getBasicRemote().sendText(toName+fromName+message);
	}
    
    
 
    public static synchronized int getOnlineCount() {
        return onlineCount;
    }
 
    public static synchronized void addOnlineCount() {
        ChatController5.onlineCount++;
    }
     
    public static synchronized void subOnlineCount() {
        ChatController5.onlineCount--;
    }

}